package hibari.server.lib;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class MultiPartRequest {
    private Map<String, FileData> datas = new HashMap<String, FileData>();
    private Map<String, String> parameters = new HashMap<String, String>();

    private HttpServletRequest request;

    public MultiPartRequest(HttpServletRequest originalRequest) {
        super();
        this.request = originalRequest;
        parse();
    }

    public FileData getData(String fieldName) {
        return this.datas.get(fieldName);
    }

    public String getParameter(String fieldName) {
        return this.parameters.get(fieldName);
    }

    public String getParameter(String fieldName, String defaultValue) {
        String value = this.parameters.get(fieldName);
        return value != null ? value : defaultValue;
    }

    public HttpServletRequest getPlainRequest() {
        return this.request;
    }

    private void parse() {
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(this.request);
            while (iter.hasNext()) {
                FileItemStream next = iter.next();

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream is = next.openStream();
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = is.read(buf)) != -1) {
                    baos.write(buf, 0, len);
                }
                baos.close();
                is.close();

                if (next.getContentType() == null) {
                    this.parameters.put(next.getFieldName(), new String(baos.toByteArray(), "UTF-8"));
                } else {
                    this.datas.put(next.getFieldName(), new FileData(next.getName(), baos.toByteArray()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
